﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;

namespace Evan.Common
{
    /// <summary>
    /// 导出Excel
    /// </summary>
    public static class ExportExcel
    {
        /// <summary>
        /// 导出文件并下载
        /// </summary>
        /// <param name="ClassId">栏目ID</param>
        /// <param name="curPage">页码 如导出全部=0</param>
        /// <param name="WhereStr">条件 不写为空</param>
        public static void ExportData(int ClassId, int curPage, string WhereStr)
        {
            dynamic expChannel = new Evan.DataBase.DbOperat("Channel").GetModel(ClassId); //拿到当前栏目
            string expTable = Evan.Template.TemplateHelper.GetTableNameByPageType(Convert.ToInt32(expChannel.PageType)); //根据当前栏目获取当前表
            List<dynamic> FieldList = new Evan.DataBase.DbOperat("Fields").GetList(string.Format("States=1 and ClassId={0}", ClassId), "SortId asc,AddTime desc"); //获取字段
            Dictionary<string, string> FieldsDic = new Dictionary<string, string>(); //拿到的字段列表
            DataTable Dt_Export = new DataTable(); //导出的数据表
            List<dynamic> Data_List = new List<dynamic>();  //查询出的数据表
            int PageSize = Convert.ToInt32(Evan.Common.CommFun.GetAppSetting("Admin_PageSize"));

            if (!string.IsNullOrEmpty(WhereStr))
            {
                WhereStr += string.Format(" and ClassId={0} and States=1", ClassId);
            }
            else {
                WhereStr = string.Format(" ClassId={0} and States=1", ClassId);
            }

            Dt_Export.Columns.Add(new DataColumn("编号No", typeof(string)));
            foreach (var item in FieldList)
            {
                FieldsDic.Add(item.Title, item.FieldName);
                Dt_Export.Columns.Add(new DataColumn(item.Title, typeof(string)));
            }

            //构建表
            //拿到的field字段里面值

            //拿到一个list
            if (curPage > 0)
            {

                Evan.Model.SysModel.PageModel _temp = new Evan.DataBase.DbOperat(expTable).GetPage_2(PageSize, curPage, WhereStr, Evan.Template.TemplateHelper.GetSqlOrderStr(expChannel.OrderBy, expChannel.SubOrderBy));
                Data_List = _temp.Item;
            }
            else
            {
                Data_List = new Evan.DataBase.DbOperat(expTable).GetList(WhereStr, Evan.Template.TemplateHelper.GetSqlOrderStr(expChannel.OrderBy, expChannel.SubOrderBy));
            }


            //填充列
            foreach (dynamic item in Data_List)
            {
                Dictionary<string, object> dataRow = Evan.Model.ConvertModel.ConvertToDictionary(item);
                DataRow dr = Dt_Export.NewRow();
                dr["编号No"] = item.Id;
                foreach (var Field in FieldsDic)
                {
                    dr[Field.Key] = dataRow[Field.Value];
                }

                Dt_Export.Rows.Add(dr);
            }

            //导出到 Excel 文件
            DataTableToExcelAndDownload(Dt_Export, expChannel.Title + "-" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".xls");
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="FileName"></param>
        public static void DataTableToExcelAndDownload(System.Data.DataTable dt, string FileName)
        {
            //创建请求处理对象
            HttpResponse resp = HttpContext.Current.Response;

            resp.Clear();
            resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);
            string colHeaders = "", ls_item = "";
            int i = 0;

            DataRow[] myRow = dt.Select("");

            //取得数据表各列标题，各标题之间以\t分割，最后一个列标题后加回车符 
            for (i = 0; i < dt.Columns.Count; i++)
            {
                if (i == dt.Columns.Count - 1)
                {
                    colHeaders += dt.Columns[i].Caption.ToString() + "\n";
                }
                else
                {
                    colHeaders += dt.Columns[i].Caption.ToString() + "\t";
                }
            }

            resp.Write(colHeaders); 

            foreach (DataRow row in myRow)
            {
                for (i = 0; i < dt.Columns.Count; i++)
                {
                    if (i == dt.Columns.Count - 1)
                    {
                        ls_item += "'" + row[i].ToString().TrimStart('=').Replace("\n", "-n-") + "\n";
                    }
                    else
                    {
                        ls_item += "'" + row[i].ToString().TrimStart('=').Replace("\n", "-n-") + "\t";
                    }
                }

                resp.Write(ls_item);
                ls_item = "";
            }

            resp.End();
        }

    }
}
